<?php
/**
 *  Collection of utilities for php servlet-like scripts
 */

define('RESPONSE_SUCCESS', 200);
define('RESPONSE_ERROR', 400);

function SendErrorResponse($message = array(), $code = null)
{
  global $RESPONSE_JSON;
  if (!is_numeric($code))
    $code = RESPONSE_ERROR;
  $RESPONSE_JSON = array('code' => $code, 'message' => $message);

  SendResponse($RESPONSE_JSON, true);
}

/**
 * Simulates a forms error response.
 * @param array $errors
 */
function SendFormsErrorResponse($errors)
{
  SendErrorResponse($errors, null, false);
}

function SendResponse($response = null, $exit = true)
{
  if (!array_key_exists('code', $response) || !array_key_exists('message', $response))
    $response = array('message' => $response);
  // send default success code if no errors found
  if (!array_key_exists('code', $response))
    $response['code'] = RESPONSE_SUCCESS;

  header('Content-type: text/html', true); // use text/html so that IE does not try to download the application/json header.
  print json_encode($response);
  if ($exit === true)
    exit(0);
}

function SendPermissionErrorResponse($permission)
{
  SendErrorResponse("Permission \"$permission\" is denied!");
}

function GetRequestData()
{
  // TODO: set to POST
//  return $_GET;
  return $_POST;
}


function HandleFatalPhpError()
{
  $last_error = error_get_last();
  if($last_error['type'] === E_ERROR)
  {
    ob_clean();
    SendErrorResponse($last_error['message'], RESPONSE_ERROR);
  }
  else if(mysql_error())
  {
    ob_clean();
    SendErrorResponse(mysql_error(), RESPONSE_ERROR);
  }
}

function GetServletPaginationData()
{
  return array(
    'sort' => $_REQUEST['sort'],
    'from' => $_REQUEST['from'],
    'to' => $_REQUEST['to'],
    'dir' => $_REQUEST['dir'],
  );
}
function SetServletPaginationData(&$response, $paginationData)
{
  $response = array(
    'items' => (array) $response,
    'total' => $paginationData['total'],
    'from' => $paginationData['from'],
    'to' => $paginationData['to'],
    'sort' => $paginationData['sort'],
  );
  if (array_key_exists('hasMore', $paginationData))
    $response['hasMore'] = (bool) $paginationData['hasMore'];
}



/* -------- MOBILE APP BEGIN -------- */
/**
 * Handles fatal php and mysql errors on mobile app ajax servlets.
 */
function HandleMobileFatalPhpError()
{
  $last_error = error_get_last();
  if($last_error['type'] === E_ERROR)
  {
    $logger = GetLogger(LOGS_PATH . 'mobile-api-errors.txt');
    $logger->LogInfo(var_export($last_error['message'], true) . ', request: ' . var_export($_REQUEST, true));
    ob_clean();
    SendMobileErrorResponse('unknown-error');
  }
  else if (mysql_error())
  {
    $logger = GetLogger(LOGS_PATH . 'mobile-api-errors.txt');
    $logger->LogInfo(mysql_error() . ', request: ' . var_export($_REQUEST, true));
    ob_clean();
    SendMobileErrorResponse('unknown-error');
  }
}

/**
 * Sends response as json for a mobile app sevlet.
 * @param string $response
 * @param <type> $exit 
 */
function SendMobileResponse($response = null, $exit = true)
{
  if (!$response['status'])
    $response['status'] = 'ok';
  header('Content-type: application/json', true);
  print mb_json_encode($response);
  if ($exit === true)
    exit(0);
}

/**
 * Sends error response as json for a mobile app sevlet.
 * @param string $response
 * @param <type> $exit
 */
function SendMobileErrorResponse($error = array())
{
  if (function_exists('GetCurrentUser'))
    $currentUser = GetCurrentUser();
    $response = array('status' => 'error', 'error' => $error);

  
  SendMobileResponse($response, true);
}

/**
 * Validates the request method.
 * @param String $type
 */
function CheckRequestMethodOrSendMobileError($type)
{
  if ($_SERVER['REQUEST_METHOD'] != $type)
    SendMobileErrorResponse('unknown-request');
}

/**
 * Checks that the user is logged in and send error if not.
 */
function CheckAuthenticationOrSendMobileError()
{
  if (!UserIsLoggedIn())
    SendMobileErrorResponse('user-not-logged-in');
}

/* -------- MOBILE APP END -------- */

?>
